package de.lulusoft.anothertorrent.gui.exceptions;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.UIJob;

import de.lulusoft.anothertorrent.core.exceptions.RTorrentNoInfoHashException;
import de.lulusoft.anothertorrent.core.exceptions.UnknownException;
import de.lulusoft.anothertorrent.core.exceptions.XmlRpcParseException;
import de.lulusoft.anothertorrent.gui.AnotherTorrentGui;

/**
 * Handles Exceptions.
 *
 */
public class ExceptionHandler {
	
	/**
	 * logs the error.
	 * @param e
	 */
	public static void handle(Throwable e)
	{
		if (e instanceof RTorrentNoInfoHashException)
		{
			IStatus status = new Status(IStatus.ERROR, AnotherTorrentGui.PLUGIN_ID, "The torrent does not exist.", e);
			AnotherTorrentGui.getDefault().getLog().log(status );
			e.printStackTrace();
		}
		else if (e instanceof XmlRpcParseException)
		{
			IStatus status = new Status(IStatus.ERROR, AnotherTorrentGui.PLUGIN_ID, "Problem parsing the XmlRpc response.", e);
			AnotherTorrentGui.getDefault().getLog().log(status );
			e.printStackTrace();
		}
		else if (e instanceof UnknownException)
		{
			IStatus status = new Status(IStatus.ERROR, AnotherTorrentGui.PLUGIN_ID, "An unknown anotherTorrent Error occurred.", e);
			AnotherTorrentGui.getDefault().getLog().log(status );
			e.printStackTrace();
		}
		else
		{ // Unknown Exception
			IStatus status = new Status(IStatus.ERROR, AnotherTorrentGui.PLUGIN_ID, "An unknown Error occurred.", e);
			AnotherTorrentGui.getDefault().getLog().log(status );
			e.printStackTrace();
		}
	}
	
	/**
	 * logs the error.
	 * @param message
	 * @param e
	 */
	public static void handle(String message, Throwable e)
	{
		IStatus status = new Status(IStatus.ERROR, AnotherTorrentGui.PLUGIN_ID, message, e);
		AnotherTorrentGui.getDefault().getLog().log(status );
		e.printStackTrace();
	}
	
	/**
	 * Logs the error and alerts the user.
	 * @param message
	 * @param e
	 */
	public static void alert(final String message, Throwable e)
	{
		final IStatus status = new Status(IStatus.ERROR, AnotherTorrentGui.PLUGIN_ID, message, e);
		AnotherTorrentGui.getDefault().getLog().log(status );
		UIJob ui = new UIJob(AnotherTorrentGui.getDefault().getWorkbench().getDisplay(), "Alert Error") {
			@Override
			public IStatus runInUIThread(IProgressMonitor monitor) {
				ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
						"An Error Occurred", message, status);
				return Status.OK_STATUS;
			}
		};
		ui.setUser(false);
		ui.setPriority(UIJob.INTERACTIVE);
		ui.schedule();
	}

}
